package com.ndp.fb.mq.service.publishhandleservice.post;

import com.ndp.fb.mq.api.service.publishhandleservice.PublishPostProcessor;
import com.ndp.fb.mq.api.service.publishhandleservice.PublishPostProcessorHandle;
import com.ndp.fb.mq.api.service.publishhandleservice.PublishPostResult;
import com.ndp.fb.util.ThreadPool;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hunk.qin on 2016/1/2.
 */
@Component
public class PublishPostProcessorHandleImpl implements PublishPostProcessorHandle,BeanPostProcessor {


    private List<PublishPostProcessor> proccessList=new ArrayList<>();

    @Override
    public void handle(final PublishPostResult publishPostResult) {

        for (PublishPostProcessor publishPostProcessor : proccessList) {
            ThreadPool.execute(() -> publishPostProcessor.processor(publishPostResult));
        }
    }

    @Override
    public void registerHandle(PublishPostProcessor publishPostProcessor) {
        proccessList.add(publishPostProcessor);
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String s) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String s) throws BeansException {
        Class<?> targetClass = AopUtils.getTargetClass(bean);
        if(ArrayUtils.contains(targetClass.getInterfaces(),PublishPostProcessor.class)){
            registerHandle((PublishPostProcessor) bean);
        }
        return bean;
    }

}
